package com.example.dayu521.sg_oss.service.impl;

import com.example.dayu521.sg_oss.domain.OssIndex;
import com.example.dayu521.sg_oss.service.OssIndexService;
import com.example.dayu521.sg_oss.service.RecordOss;
import lombok.extern.slf4j.Slf4j;
import org.example.dayu521.oss.Mq;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.function.BiFunction;

@Slf4j
public class RecordOssImpl implements RecordOss {

    private OssIndexService ossIndexService;

    private RabbitTemplate rabbitTemplate;

    public RecordOssImpl(OssIndexService ossIndexService, RabbitTemplate rabbitTemplate) {
        this.ossIndexService = ossIndexService;
        this.rabbitTemplate = rabbitTemplate;
    }

    private BiFunction<String,String,Boolean> delegate;
    @Override
    public void locale(LocalFileOss localFileOss) {
        //不需要记录,因为上传时已经被记录
        delegate=(obj,passwd)->{
            return true;
        };
    }

    @Override
    public void minio(MinioOss minioOss) {
        delegate=(obj_name,passwd)->{
            boolean save=false;
            try {
                save = ossIndexService.lambdaUpdate().eq(OssIndex::getObj_name,obj_name).set(OssIndex::getStatus,1).update();
            }catch (DuplicateKeyException e){
                log.error("{},obj对象已存在:[{}],恢复中",minioOss.oss_identify(),obj_name);
                OssIndex ossIndex = ossIndexService.lambdaQuery().eq(OssIndex::getObj_name, obj_name).one();
                if(ossIndex==null){
                    log.error("不存在此记录 {}",obj_name);
                    return true;
                }
                rabbitTemplate.convertAndSend("sg_oss.recover.exchange","obj_duplicate."+minioOss.oss_identify()
                        ,new Mq.Recover(ossIndex.getId(),ossIndex.getObj_name()));
                return false;
            }
            if(!save){
                log.error("obj记录失败:{}",obj_name);
                return false;
            }
            return true;
        };
    }

    @Override
    public boolean record(String obj_name, String passwd) {
        return delegate.apply(obj_name,passwd);
    }

    @Override
    public String identify(String obj_name) {
        return "";
    }
}
